﻿using System;
using System.Threading;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using underwater.Processes;
using System.Xml;
using System.IO;

namespace underwater.OS
{
    class OpSys
    {
        #region Размеры мира
        public static int WorldWidth { get { return 10000; } }
        public static int WorldHeight { get { return 4000; } }
        public static int DnoHeight { get { return Loader.Textures[TextureEnum.Bottom].Height; } }
        public static int WaterBegin { get { return Loader.Textures[TextureEnum.Sky].Height; } }
        public static int WaterHeight { get { return WorldHeight - WaterBegin - DnoHeight; } }
        public static int DnoBegin { get { return WaterBegin + WaterHeight; } }
        #endregion

        public static Random rand = new Random(DateTime.Now.Millisecond);
        List<Process> Processes; // очередь процессов
        public enum ProcessTypes // типы процессов
        {
            None, Bubble, Cloud, Weed, SmallFish, Shark, VioletFish, Skeleton, TurquoiseFish, RoboFish, YellowFish, Nibbler, RedFish
        //   0      1       2       3       4       5       6           7           8           9           10          11      12
        }

        Interpritator inter; // интерпритатор   
        #region Управление ОС
        KeyboardState keyboard;
        public static int ScrlX, ScrlY;
        //двигаем координаты экрана         
        public static void ScrollX(int dx)
        {
            if (ScrlX + dx >= 0 && ScrlX + dx <= WorldWidth - Game1.Width)
                ScrlX += dx;
        }
        public static void ScrollY(int dy)
        {
            if (ScrlY + dy >= 0 && ScrlY + dy <= WorldHeight - Game1.Height)
                ScrlY += dy;
        }
        //переобразовуем координты экранна в мировые
        public static Rectangle GetSR(Rectangle rect)
        {
            Rectangle r = rect;
            r.Offset(-ScrlX, -ScrlY);
            return r;
        }
        #endregion

        public OpSys()
        {
            inter = new Interpritator();
            Processes = new List<Process>();

            // добавляем акул...
            Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\Shark.xml"));
            Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\Shark.xml"));
            Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\Shark.xml"));
            Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\Shark.xml"));
            for (int i = 0; i < 20; i++)
            {
                Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\VioletFish.xml"));
                Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\TurquoiseFish.xml"));
            }
        }
        Process CreateProcessAndLoadCodeFromFile(string Path)
        {
            Process proc = new Process();
            FileStream fs = new FileStream(Path, FileMode.Open);
            proc.KOD.Load(fs);
            fs.Close();
            inter.InitProc(proc);
            return proc;
        }
        int ElapsedTimeCloud = 0;
        int FishElapsedTime = 0;
        int BubbleCreate = 0;
        UsersMenu UM = new UsersMenu();
        KeyboardState old = Keyboard.GetState();
        bool MenuShow = false;

        public void Update(GameTime gametime)
        {
            keyboard = Keyboard.GetState();
            MouseState m = Mouse.GetState();
            //мышка двигает координаты экрана по мировым
            if (m.X < 5 || keyboard.IsKeyDown(Keys.Left)) ScrollX(-25);
            if (m.X > Game1.Width - 25 || keyboard.IsKeyDown(Keys.Right)) ScrollX(25);
            if (m.Y < 5 || keyboard.IsKeyDown(Keys.Up)) ScrollY(-25);
            if (m.Y > Game1.Height - 25 || keyboard.IsKeyDown(Keys.Down)) ScrollY(25);
            // ескейп для выхода в меню            
            if (keyboard.IsKeyDown(Keys.Escape))
                Game1.State = OSstate.Menu;
            if (keyboard.IsKeyUp(Keys.M) && old.IsKeyDown(Keys.M))
                MenuShow = !MenuShow;
            ElapsedTimeCloud += gametime.ElapsedGameTime.Milliseconds;
            FishElapsedTime += gametime.ElapsedGameTime.Milliseconds;
            BubbleCreate += gametime.ElapsedGameTime.Milliseconds;
            if (Processes.Count < 250)
            {
                if (ElapsedTimeCloud > 300)
                {
                    Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\Clouds.xml"));
                    ElapsedTimeCloud = 0;
                }
                if (FishElapsedTime > 1000)
                {
                    Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\VioletFish.xml"));
                    Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\TurquoiseFish.xml"));
                    FishElapsedTime = 0;
                }
                if (BubbleCreate > 100)
                {
                    Processes.Add(CreateProcessAndLoadCodeFromFile(@"Content\Processes\bubble.xml"));
                    BubbleCreate = 0;
                }
            }
            // меню
            if (MenuShow) 
                UM.Update(gametime,ref Processes);
            inter.Update(Processes,gametime);
            old = keyboard;
        }
        
        public void Draw(SpriteBatch spritebatch,GameTime gameTime)
        {
            spritebatch.Begin();
            //вода
            spritebatch.Draw(Loader.Textures[TextureEnum.Water], GetSR(new Rectangle(0, WaterBegin, WorldWidth, WaterHeight)), new Rectangle(0, 0, Loader.Textures[TextureEnum.Water].Width, Loader.Textures[TextureEnum.Water].Height), Color.White);
            //небо 
            for (int i = 0; i < WorldWidth; i += Loader.Textures[TextureEnum.Sky].Width)
                spritebatch.Draw(Loader.Textures[TextureEnum.Sky], new Rectangle(i - ScrlX, -ScrlY, Loader.Textures[TextureEnum.Sky].Width, Loader.Textures[TextureEnum.Sky].Height), Color.White);
            //дно
            for (int i = 0; i < WorldWidth; i += Loader.Textures[TextureEnum.Bottom].Width)
                spritebatch.Draw(Loader.Textures[TextureEnum.Bottom], new Rectangle(i - ScrlX, DnoBegin - ScrlY, Loader.Textures[TextureEnum.Bottom].Width, Loader.Textures[TextureEnum.Bottom].Height), Color.White);
            foreach (Process k in Processes)
                inter.Draw(k,spritebatch,gameTime);
            if (MenuShow)
                UM.Draw(spritebatch);
            spritebatch.End();
        }

        void Menu(SpriteBatch spritebatch, GameTime gameTime)
        {
            
        }
    }
}
